package com.deercrowing.takeaway.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deercrowing.takeaway.common.constant.MessageConstant;
import com.deercrowing.takeaway.common.constant.StatusConstant;
import com.deercrowing.takeaway.common.exception.BusinessException;
import com.deercrowing.takeaway.context.BaseContext;
import com.deercrowing.takeaway.dao.EmployeesMapper;
import com.deercrowing.takeaway.entity.EmployeesEntity;
import com.deercrowing.takeaway.service.EmployeesService;
import com.deercrowing.takeaway.vo.EmployeeEditPasswordVO;
import com.deercrowing.takeaway.vo.EmployeesPageVO;
import com.deercrowing.takeaway.vo.EmployeesVO;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工信息(Employees)表服务实现类
 *
 * @author guoyongxiang
 * @since 2024-07-05 17:29:13
 */
@Service
@Slf4j
public class EmployeesServiceImpl extends ServiceImpl<EmployeesMapper, EmployeesEntity> implements EmployeesService {

    @Autowired
    EmployeesMapper employeesMapper;

    @Override
    public EmployeesVO login(EmployeesVO employeesVO) {
        String username = employeesVO.getUsername();
        String password = employeesVO.getPassword();

        EmployeesVO employees = employeesMapper.getUserByUsername(username);

        /**
         * TODO 账号错误，异常类（待添加）
         */
        if(ObjectUtils.isEmpty(employees)){
            throw new BusinessException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        /**
         * TODO MD5密码比对失败，密码错误，异常类（待添加）
         */
        if (!password.equals(employees.getPassword())){
            throw new BusinessException(MessageConstant.PASS_ERROR);
        }

        /**
         * TODO 账号状态
         */
        if (employees.getStatus() == StatusConstant.DISABLE){
            throw new BusinessException(MessageConstant.ACCOUNT_LOCKED);
        }

        return employees;
    }

    @Override
    public void compareByContext(EmployeesVO employeesVO, Integer isAddOrUpdate) {
        Integer userid = employeesVO.getId();
        String username = employeesVO.getUsername();
        String phone = employeesVO.getPhone();

        /**
         * TODO 手机长度校验
         */
        if (phone.length() > 11){
            throw new BusinessException(MessageConstant.PHONE_TO_LONG);
        }

        /**
         * 存在相同账号(更新操作未更改账户时不验证)，不提交
         */
        List<EmployeesEntity> emList = employeesMapper.seleteList();
        if (isAddOrUpdate == 2) {
            for (EmployeesEntity employee : emList) {
                if (username.equals(employee.getUsername()) && userid != employee.getId()) {
                    throw new BusinessException(MessageConstant.USER_ALREADY_EXISTS);
                }
            }
        }else {
            for (EmployeesEntity employee : emList) {
                if (username.equals(employee.getUsername())) {
                    throw new BusinessException(MessageConstant.USER_ALREADY_EXISTS);
                }
            }
        }
    }

    @Override
    public void employeeStatusUpdate(Short status, Integer id) {
        if (ObjectUtils.isEmpty(employeesMapper.selectById(id))){
            throw new BusinessException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        employeesMapper.updateByStatus(status, id);
    }

    @Override
    public IPage<EmployeesVO> searchByCondition(EmployeesPageVO employeePageVO) {
        int page = employeePageVO.getPage() == null ? 0 : employeePageVO.getPage();
        int pageSize = employeePageVO.getPageSize() == null ? 10 : employeePageVO.getPageSize();

        // 设置sql语句中limit分页查询
        Integer limit = (page - 1) * pageSize;
        employeePageVO.setPage(limit);
        employeePageVO.setPageSize(pageSize);

        List<EmployeesEntity> employeesEntityList = employeesMapper.selectListByCondition(employeePageVO);

        if (employeesEntityList.size() < 0){
            throw new BusinessException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        List<EmployeesVO> employeesVOList = employeesEntityList.stream()
                .map(source -> new EmployeesVO(
                        source.getId(),
                        source.getName(),
                        source.getUsername(),
                        source.getPassword(),
                        source.getPhone(),
                        source.getSex(),
                        source.getIdNumber(),
                        source.getStatus(),
                        source.getUpdateTime()))
                .collect(Collectors.toList());

        Integer count = employeesMapper.countEmployeesNum(employeePageVO);
        IPage<EmployeesVO> entityIPage = new Page<>(page, pageSize);
        entityIPage.setRecords(employeesVOList);
        entityIPage.setTotal(count);

        return entityIPage;
    }

    @Override
    public EmployeesVO selectById(Long id) {
        EmployeesEntity employeesEntity = employeesMapper.selectById(id);
        if (employeesEntity == null){
            throw new BusinessException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        EmployeesVO employeesVO = new EmployeesVO();
        BeanUtils.copyProperties(employeesEntity, employeesVO);

        return employeesVO;
    }

    @Override
    public void updateInfoToDB(Long id, EmployeesVO employeesVO) {
        EmployeesEntity entity = employeesMapper.selectById(id);
        if (ObjectUtils.isEmpty(entity) || ObjectUtils.isEmpty(employeesVO))
        {
            throw new BusinessException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 对比信息
        compareByContext(employeesVO,2);

        // 更新用户数据
        entity.setName(employeesVO.getName())
              .setIdNumber(employeesVO.getIdNumber())
              .setPassword(employeesVO.getPassword())
              .setSex(employeesVO.getSex())
              .setPhone(employeesVO.getPhone())
              .setUpdateTime(LocalDateTime.now())
              .setUpdateEmployee(BaseContext.getCurrentId().intValue())
              .updateById();
    }

    @Override
    public void insertInfoToDB(EmployeesVO employeesVO) {
        // 对比信息
        compareByContext(employeesVO,1);

        EmployeesEntity entity = new EmployeesEntity();
        BeanUtils.copyProperties(employeesVO,entity);

        String encodePassword = DigestUtils.md5Hex("123456");

        // 新增数据
        entity.setId(0)
              .setPassword(encodePassword)
              .setStatus(StatusConstant.DISABLE)
              .setCreateTime(LocalDateTime.now())
              .setUpdateTime(LocalDateTime.now())
              .setCreateEmployee(BaseContext.getCurrentId().intValue())
              .setUpdateEmployee(BaseContext.getCurrentId().intValue())
              .insert();
    }

    @Override
    public void changePassword(EmployeeEditPasswordVO employeeEditPasswordVO) {
        EmployeesEntity entity = employeesMapper.selectById(BaseContext.getCurrentId());

        if (employeeEditPasswordVO.getNewPassword() == null){
            throw new BusinessException(MessageConstant.PLEASE_INPUT_NEW_PASSWORD);
        }

        if (employeeEditPasswordVO.getOldPassword() == null){
            throw new BusinessException(MessageConstant.PLEASE_INPUT_OLD_PASSWORD);
        }

        if (!entity.getPassword().equals(employeeEditPasswordVO.getOldPassword())){
            throw new BusinessException(MessageConstant.OLD_PASSWORD_FAILED);
        }

        if (entity.getPassword().equals(employeeEditPasswordVO.getNewPassword())){
            throw new BusinessException(MessageConstant.NEW_OLD_PASSWORD_NO_EQUAL);
        }

        // 修改密码
        entity.setPassword(employeeEditPasswordVO.getNewPassword())
              .updateById();
    }
}

